package worst.shopping.lists;

import database.DataBaseKeys;
import database.ListDAO;
import database.ProductDAO;
import worst.shopping.R;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import android.widget.ListView;

public class CreateListActivity extends ListActivity {
	private ProductDAO _productDAO;
	private Cursor _productCursor;
	private CreateListHighlightableImageCursorAdapter _adapter;
	
	private EditText _listName;
	private ListDAO _listDAO;
	private MyViewBinder _viewBinder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.managelistactivity_layout);

		_listName = (EditText)this.findViewById(R.id.createlistactivity_listname_edittext);
		_productDAO = new ProductDAO(getApplication());
		_listDAO = new ListDAO(getApplication());
		_productCursor = _productDAO.getAllProductsCursor();

		startManagingCursor(_productCursor);
		
		setUpListView();	
		
		final EditText listNameEditText = (EditText)this.findViewById(R.id.createlistactivity_listname_edittext);
		
		listNameEditText.setOnEditorActionListener(new OnEditorActionListener() {

	        public boolean onEditorAction(TextView v, int actionId,
	                KeyEvent event) {
	            if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
	                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	                in.hideSoftInputFromWindow(listNameEditText
	                        .getApplicationWindowToken(),
	                        InputMethodManager.HIDE_NOT_ALWAYS);
	            }
	            return false;
	        }
	    });		
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		_listDAO.clearTemporaryTable();
	}
	
	private void setUpListView() {
		ListView listView = getListView();
		
		_adapter = new CreateListHighlightableImageCursorAdapter
				(this, 
				R.layout.listitem_withextra, _productCursor, 
				new String[] { DataBaseKeys.PRODUCT_NAME, DataBaseKeys.PRODUCT_ICON }, 
				new int[]{ R.id.list_item_name, R.id.list_item_image}, getResources().getDrawable(R.drawable.gradient), _listDAO, null);


		_viewBinder = new MyViewBinder();
		_adapter.setViewBinder(_viewBinder);
		listView.setAdapter(_adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> adapterview, View view, int pos,
					long id) {
	        	_productCursor.moveToPosition(pos);
				final String productname = _productCursor.getString(_productCursor.getColumnIndex(DataBaseKeys.PRODUCT_NAME));
				final EditText countEditText = new EditText(CreateListActivity.this);
				countEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
				
				AlertDialog.Builder builder = new AlertDialog.Builder(CreateListActivity.this);
				builder.setView(countEditText);
				builder.setTitle("Amount")
				       .setCancelable(true);
				
				//if item is already selected
				//let user choose to change the count or remove the selection
				if(_listDAO.isInTemporaryTable(productname))
				{	
					countEditText.setText("" + _listDAO.getCountOfProductInTemporaryTable(productname));
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					        	   int count = Integer.parseInt(countEditText.getText().toString());
					        	   _listDAO.updateTemporaryTable(
					        			productname,
					        			count);
					        	   _viewBinder.selectedCount.put(productname, countEditText.getText().toString());
					        	   _adapter.notifyDataSetChanged();
					           }
					       })
					       .setNegativeButton("Remove", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					        	   _listDAO.removeFromTemporaryTable(productname);
					        	   _viewBinder.selectedCount.remove(productname);
					        	   _adapter.notifyDataSetChanged();
					           }
					       });
				}
				else
				{
					countEditText.setText("1");
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					        	   _listDAO.insertIntoTemporaryTable(
					        			productname,
					        			Integer.parseInt(countEditText.getText().toString()));
					        	   _viewBinder.selectedCount.put(productname, countEditText.getText().toString());
					        	   _adapter.notifyDataSetChanged();
					           }
					       })
					       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dialog.cancel();
					           }
					       });	
				}
				builder.create().show();
			}
		});			
	}
	
	public void saveButtonClicked(View view)
	{
		String listname = _listName.getText().toString();
		
		//database already contains list?	
		if(_listDAO.listExists(listname))
		{
			showListAlreadyExistsError(listname);
		}
		else
		{
			_listDAO.insertList(listname);
			_listDAO.saveListFromTemporaryToPersistant(listname);
			_listDAO.clearTemporaryTable();
			finish();
		}
	}
	
	private void showListAlreadyExistsError(String listname) {
		AlertDialog.Builder builder = new AlertDialog.Builder(CreateListActivity.this);
		builder.setTitle("Sorry!");
		builder.setMessage("Listname " + listname +" already taken");
		builder.setCancelable(false);
		builder.setNeutralButton("Ok", null);
		builder.create().show();
	}

	public void cancelButtonClicked(View view)
	{
		_listDAO.clearTemporaryTable();
		finish();
	}
}
